package com.whfc.fmam.interceptor;

import com.whfc.common.exception.BizException;
import com.whfc.common.result.ResultEnum;
import com.whfc.fmam.entity.constant.FmamConstant;
import com.whfc.fmam.entity.dto.FmamClientDTO;
import com.whfc.fmam.service.FmamApiTokenService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author xuguocheng
 * @desc 拦截器, 一些接口必须注册才能访问.
 * @date 2019-08-03
 */
@Component
public class MamClientIntercepter implements HandlerInterceptor {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @DubboReference(interfaceClass = FmamApiTokenService.class, version = "1.0.0")
    private FmamApiTokenService fmamApiTokenService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        logger.info("preHandle,uri:{}", request.getRequestURI());
        //验证accessToken
        String accessToken = request.getParameter("accessToken");
        if (StringUtils.isEmpty(accessToken)) {
            throw new BizException(ResultEnum.PARAM_ERROR.getCode(), "缺少accessToken参数");
        }
        FmamClientDTO fmamClientDTO = fmamApiTokenService.validateAccessToken(accessToken);
        request.setAttribute(FmamConstant.FMAM_CLIENT, fmamClientDTO);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        logger.info("postHandle,uri:{}", request.getRequestURI());
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        logger.info("afterCompletion,uri:{}", request.getRequestURI());
    }
}
